const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    newGoods: [],
    hotGoods: [],
    topics: [],
    brands: [],
    groupons: [],
    floorGoods: [],
    banner: [],
    channel: [],
    coupon: [],
    articles:[],
    goodsCount: 0,
    indicatorDots: false,
    window: false,
    colseCoupon:false,
    sign:false,
    points:'',
    endTime:'',
    countdownTime:true,
    hours:'',
    minutes:'',
    seconds:'',
    text1:' < 1 元 = 1 成长值，满 388 成长值享 85 折，满 1918 成长值享8折!>',
    goodsList:[],
    intervalTime:true,
    picUrlQG:''
  },

  onShareAppMessage: function() {
    let userInfo = wx.getStorageSync('userInfo');
    let shareUserId = 1;
    if (userInfo){
      shareUserId = userInfo.userId;
    }
    console.log('/pages/index/index?shareUserId=' + shareUserId);
    return {
      title: '观智九龙口商城',
      // imageUrl: 'https://example.com/shareImg.png', // 分享图标 
      desc: '观智科技',
      path: '/pages/index/index?shareUserId=' + shareUserId
    }
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function() {
    let that = this;
    util.request(api.IndexUrl).then(function(res) {
      // console.log('api.IndexUrl',res)
      if (res.errno === 0) {
        that.setData({
          newGoods: res.data.newGoodsList,
          hotGoods: res.data.hotGoodsList,
          topics: res.data.topicList,
          brands: res.data.brandList,
          floorGoods: res.data.floorGoodsList,
          banner: res.data.banner,
          articles: res.data.articles,
          groupons: res.data.grouponList,
          channel: res.data.channel,
          coupon: res.data.couponList
        });
       
      }
    });
    util.request(api.GoodsCount).then(function (res) {
      that.setData({
        goodsCount: res.data.goodsCount
      });
    });
  },
  onLoad: function(options) {


    
    this.setData({
      colseCoupon: false
    });
    //如果有分享用户，则设置
    if (options.shareUserId){
      wx.setStorageSync('shareUserId', options.shareUserId);
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.scene) {
      //这个scene的值存在则证明首页的开启来源于朋友圈分享的图,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      var scene = decodeURIComponent(options.scene);
      console.log("源于朋友圈分享的图scene:" + scene);

      let info_arr = [];
      info_arr = scene.split(',');
      let _type = info_arr[0];
      let id = info_arr[1];

      let shareUserId = null;//默认用户
      if (info_arr.length == 4 && info_arr[2] == 'user'){
    	  shareUserId = info_arr[3];
      } else if (_type == 'user'){
    	  shareUserId = id;
      }

	  if (shareUserId != null){
	  	 wx.setStorageSync('shareUserId', id);
	  }
  	
      if (_type == 'goods') {
        wx.navigateTo({
          url: '../goods/goods?id=' + id
        });
      } else if (_type == 'groupon') {
        wx.navigateTo({
          url: '../goods/goods?grouponId=' + id
        });
      } else if (_type == 'brand') {
          wx.navigateTo({
              url: '../brandDetail/brandDetail?id=' + id
            });
      } else if (_type == 'topic') {
           wx.navigateTo({
               url: '../topicDetail/topicDetail?id=' + id
             });
      } else {
        wx.navigateTo({
          url: '../index/index'
        });
      }
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.grouponId) {
      //这个pageId的值存在则证明首页的开启来源于用户点击来首页,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?grouponId=' + options.grouponId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.goodId) {
      //这个goodId的值存在则证明首页的开启来源于分享,同时可以通过获取到的goodId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../goods/goods?id=' + options.goodId
      });
    }

    // 页面初始化 options为页面跳转所带来的参数
    if (options.orderId) {
      //这个orderId的值存在则证明首页的开启来源于订单模版通知,同时可以通过获取到的pageId的值跳转导航到对应的详情页
      wx.navigateTo({
        url: '../ucenter/orderDetail/orderDetail?id=' + options.orderId
      });
    }

    this.getIndexData();
  },
  onReady: function() {
    // 页面渲染完成
    let that = this;
    let userinfo = wx.getStorageSync('userInfo');
   
    if (!that.data.colseCoupon && userinfo && that.data.coupon.length > 0) {
      that.setData({ window: true });
    }
  },
  async onShow() {
    // 每次页面显示，需获取是否用户登录，如果用户登录，则查询用户是否有优惠券，有则弹出优惠券领取窗口
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo){
      //优惠券
     
      util.request(api.GetUserCoupon, null, 'GET').then(res => {
       
        if (res.errno === 0) {
		    that.setData({
		          coupon: res.data.couponList
		   });

		   if (!that.data.colseCoupon && userInfo && that.data.coupon.length > 0) {
		      that.setData({ window: true });
		   } else {
		      that.setData({window:false});
		   }
        }
      })
      //签到
      //获取用户的登录信息
      let userInfo = wx.getStorageSync('userInfo');
      let userId =userInfo.userId
      if(!userInfo){
        return
      }
      util.request(api.points, {uid:userId}, 'GET').then(res => {
      //  console.log('获取签到10',res,api.points);
       if(res.code==200){
         var points = res.data
        if (!points || points.signStatus ==0 && userInfo ) {
          util.request(api.pointsSign, {uid:userId}, 'GET').then(res => {
            this.setData({
              sign:true
             })
          })
          return
        }
         wx.setStorageSync('points', points);
         let  pointsSignStatus = points.signStatus
        //  console.log('pointsSignStatus',pointsSignStatus);
         if(!pointsSignStatus){
          pointsSignStatus = 0
         }
         if(pointsSignStatus ==0){
          this.setData({
            points,
            sign:true
           })
         }else{
           
          this.setData({
            sign:false
           })
         }
         
       }
      })
      //限售商品
   var res = await  util.request(api.GoodsList, {
        isHot: true,
        page: 1,
        size: 1,
        order: 'desc',
        sort: 'browse',
        categoryId: 0})
        if (res.errno === 0) {
     
          that.setData({
            goodsList: res.data.goodsList,
            picUrlQG:res.data.goodsList[0]
          });
          console.log('res.data.goodsList[0]',res.data.goodsList[0]);
          
        }
    }
    if(this.data.countdownTime){
      this.interval()
    }
   

  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
 
  onColse: function () {
    this.setData({
       window: false,
       colseCoupon:true
     });
    // console.log('测试',this.data.window);
  },
  getCoupon(e) {
    
    if (!app.globalData.hasLogin) {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let couponId = e.currentTarget.dataset.index
    util.request(api.CouponReceive, {
      couponId: couponId
    }, 'POST').then(res => {
      if (res.errno === 0) {
        wx.showToast({
          title: "领取成功"
        })
      }
      else{
        util.showErrorToast(res.errmsg);
      }
    })
  },
  popup(){
    let userInfo = wx.getStorageSync('userInfo');
    let userId =userInfo.userId
    // console.log('userId ',userId );
   
    util.request(api.pointsSign, {uid:userId}, 'GET').then(res => {
    // console.log('res',res);
    })

  this.setData({
    sign:false
  })
  

   
  },

  interval(){
    let that = this
   if(this.data.goodsList.length==0){
     return
   }
   var timeday = this.data.goodsList[0].updateTime
   var duration = this.data.goodsList[0].duration

   
    var endTime01 = new Date(timeday).getTime();
    var endTime03 =endTime01+60*1000*60*duration
    
    var endTime = new Date(endTime03).getTime();
  var myTime = setInterval(function () {
    var now = new Date().getTime();
    var distance = endTime -now;
    if (distance < 0) {
        clearInterval(myTime );
      // console.log('获取');
      that.setData({
        intervalTime:false
        
      })
      util.request(api.GoodsUpdate,{
        id:that.data.goodsList[0].id,
        isHot:false,
       },'POST').then(res=>{
        console.log('测试获取',res);
       })
      

    }
 
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    // console.log( hours + "小时 ",distance);
    var  hours = days*24 + hours
    if(hours < 10){
      hours = '0'+ hours
    }
    if(minutes < 10){
      minutes = '0'+minutes
    }
    if(seconds < 10){
      seconds = '0'+ seconds
    }
    that.setData({
      hours,
      minutes,
      seconds
    })
}, 1000)

this.setData({
  countdownTime:false
})
  },

delistingProducts(){

},
couponsItem(e){
  let userInfo = wx.getStorageSync('userInfo');
  // console.log('point',userInfo);
  if(!userInfo){
    wx.showToast({ title: '请先登录', icon: 'none', duration: 1000 })
    return
  }
  let couponId = e.currentTarget.dataset.id
  let point = e.currentTarget.dataset.num
  let pointsNum = wx.getStorageSync('points');
  if(pointsNum.points < point){
    wx.showToast({ title: '积分不够', icon: 'none', duration: 1000 })
    return
  }
  wx.showModal({
    title: '优惠券',
    content: '是否兑换？',
    success (res) {
      if (res.confirm) {
        // console.log('用户点击确定')
        util.request(api.PointsExchange,{
          uid:userInfo.userId,
          point:point,
          couponId:couponId
        }).then(function(res){
        var pointsNumS = pointsNum.points - point
        // console.log('pointsNumS',pointsNumS);

        var pointsXG = pointsNum
        pointsXG.points = pointsNumS
         wx.setStorageSync('points',pointsXG);
          
        })
      } else if (res.cancel) {
      
        console.log('用户点击取消')
      }
    }
  })
}

})